<template>
  <div>
    <el-form
      ref="form"
      :model="filterParams"
      :label-position="'top'"
      :rules="rules">
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="filterParams.phone"></el-input>
      </el-form-item>
      <el-form-item label="注册时间" prop="rangeDate">
        <el-date-picker
            v-model="filterParams.rangeDate"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="yyyy-MM-dd"
          />
      </el-form-item>
      <el-form-item>
        <el-button
          class="checkbtn"
          @click="findItem"
          type="primary"
          :disabled="loading">查询</el-button>
        <el-button
          class="checkbtn"
          @click="resetItem"
          :disabled="loading">重置</el-button>
      </el-form-item>

    </el-form>
    <el-card>
      <el-table
        :data="users"
        style="width: 100%"
        v-loading='loading'>
        <el-table-column
          prop="id"
          label="用户ID"
          width="180">
        </el-table-column>
        <el-table-column
          prop="name"
          label="用户名"
          width="180">
        </el-table-column>
        <el-table-column
          prop="phone"
          label="手机号"
          width="180">
        </el-table-column>
        <el-table-column
          prop="createTime"
          label="注册时间"
          align="center">
        </el-table-column>
        <el-table-column
          label="状态"
          align="center">
          <template slot-scope="{row}">
            <i :class="row.status !== 'ENABLE'?status_g:status_r"></i>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center">
          <template slot-scope="{row}">
            <el-button :disabled="loading" type="text">禁用</el-button>
            <el-button
              type="text"
              :disabled="loading"
              @click="handleSelectRole(row)">分配角色</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page.sync="filterParams.currentPage"
      :page-sizes="[3, 5, 7, 9]"
      :page-size="filterParams.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalCount"
      class="pagepos">
    </el-pagination>
    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="30%">
      <el-select v-model="selectVal" multiple placeholder="请选择">
        <el-option
          v-for="role in roles"
          :key="role.id"
          :label="role.name"
          :value="role.id">
        </el-option>
      </el-select>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleAllocRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script lang=ts>
import { allocateUserRoles, findUserAllRoles, getAllRole } from '@/services/role'
import { getUserPages } from '@/services/user'
import { Form } from 'element-ui'
import Vue from 'vue'
export default Vue.extend({
  name: 'UserIndex',
  data () {
    const validatorPhone = (rule:RegExp, value:string, callback:any) => {
      if (value === '') {
        callback(new Error('请输入手机号'))
      } else {
        if (!/^1[3456789]\d{9}$/.test(value)) {
          callback(new Error('请输入正确的手机号'))
        } else {
          callback()
        }
      }
    }
    return {
      users: [],
      filterParams: {
        currentPage: 1,
        pageSize: 5,
        phone: '',
        startCreateTime: '',
        endCreateTime: '',
        rangeDate: []
      },
      totalCount: 0,
      loading: true,
      rules: {
        phone: [
          { required: true, validator: validatorPhone, trigger: 'blur' }
        ]
      },
      dialogVisible: false,
      selectVal: [],
      roles: [],
      currentRow: null,
      status_g: 'status_icon_g',
      status_r: 'status_icon_r'
    }
  },
  methods: {
    handleSizeChange (val:any) {
      // console.log(`每页 ${val} 条`)
      this.filterParams.pageSize = val
      this.filterParams.currentPage = 1
      this.loadUsers()
    },
    handleCurrentChange (val:any) {
      // console.log(`当前页: ${val}`)
      this.filterParams.currentPage = val
      this.loadUsers()
    },
    async loadUsers () {
      this.loading = true
      const { rangeDate } = this.filterParams
      if (rangeDate && rangeDate.length) {
        this.filterParams.startCreateTime = rangeDate[0]
        this.filterParams.endCreateTime = rangeDate[1]
      } else {
        this.filterParams.startCreateTime = ''
        this.filterParams.endCreateTime = ''
      }
      const { data } = await getUserPages(this.filterParams)
      // console.log(data)
      this.users = data.data.records
      this.totalCount = data.data.total
      this.loading = false
    },
    async findItem () {
      try {
        await (this.$refs.form as Form).validate()
        // if (!bol) {
        //   return this.$message.error('查询参数错误，请修改')
        // }
        this.filterParams.currentPage = 1
        this.loadUsers()
      } catch (err) {
        this.$message.error('查询参数错误')
        this.resetItem()
      }
    },
    resetItem () {
      (this.$refs.form as Form).resetFields()
      this.filterParams.currentPage = 1
      this.loadUsers()
    },
    // handlerSrc (row:any):string {
    //   return row.status !== 'ENABLE'
    //     ? require('@/assets/status_open.png')
    //     : require('@/assets/status_cls.png')
    // },
    async handleSelectRole (row:any) {
      this.currentRow = row
      const { data } = await getAllRole()
      // console.log(data)
      this.roles = data.data

      const { data: { data: userRoles } } = await findUserAllRoles(row.id)
      // console.log(userRoles)
      this.selectVal = userRoles.map((item:any) => item.id)

      this.dialogVisible = true
    },
    async handleAllocRole () {
      const { data } = await allocateUserRoles({
        userId: (this.currentRow as any).id,
        roleIdList: this.selectVal
      })
      // console.log(data)
      if (data.code === '000000') {
        this.$message.success('分配成功')
        this.dialogVisible = false
      }
    }
  },
  created () {
    this.loadUsers()
  }
})
</script>

<style lang="scss" scoped>
.el-form{
  display: flex;
  align-items: center;
}
.el-form-item{
  display: inline-block;
  margin-right: 1rem;
}
.checkbtn{
  margin-top: 3rem;
}
.line{
  text-align: center;
}
.pagepos{
  display: flex;
  justify-content: end;
}
.status_icon_g:before{
  content: '';
  background-color: #51cf66;
  display: inline-block;
  width: 15px;
  height: 15px;
  border-radius: 50%;
}
.status_icon_r:before{
  content: '';
  background-color: #ff6b6b;
  display: inline-block;
  width: 15px;
  height: 15px;
  border-radius: 50%;
}
</style>
